package com.yangming.controller;

import com.yangming.common.base.BaseController;
import com.yangming.common.base.BaseResponseEnum;
import com.yangming.common.base.SystemProperties;
import com.yangming.common.utils.BackJsonBeanUtil;
import com.yangming.common.utils.CheckUtil;
import com.yangming.common.utils.OauthUtil;
import com.yangming.common.utils.SpringUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 微信消息入口
 * @author PengShuiMing
 * @create 2018-09-10
 **/
@RestController
@RequestMapping("/wechat")
public class WeChatController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(WeChatController.class);
    @Autowired
    private WxMpService wxMpService;
    /**
     * 校验信息是否是从微信服务器发出，处理消息
     *
     */
    @RequestMapping("/public/handler")
    public void processPost() throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        logger.info("开始校验信息是否是从微信服务器发出");

        // 签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败

        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
            // 随机字符串
            String echostr = request.getParameter("echostr");
            logger.debug("接入成功，echostr {}", echostr);
            this.response.getWriter().write(echostr);
        }
    }
    /**
     * 获取openId
     * @param code
     * @param echostr
     * @param request
     * @return
     */
    @RequestMapping("/public/{name}/getOpenId")
    public Object getOpenId(String code, String echostr, HttpServletRequest request, @PathVariable(value="name") String name) {
        String result =null;
        BaseResponseEnum baseResponseEnum = BaseResponseEnum.ERROR_NOT_AUTHENTICATION;
        try {
            if(StringUtils.isNotBlank(code)){
                result = SpringUtil.getBeanByClass(OauthUtil.class).getOpenId(code,request);
                if(StringUtils.isNotBlank(result)){
                    baseResponseEnum = BaseResponseEnum.SUCCESS_AUTHENTICATION;
                }
            }else{
                result = echostr;
            }
        } catch (Exception e) {
            logger.error("[获取openId]",e.getMessage(),e);
        }
        return BackJsonBeanUtil.getBackJsonBean(baseResponseEnum,result);
    }
    @RequestMapping("/sendTemplateMessage")
    public Object sendTemplateMessage() throws WxErrorException {
        String openId = this.getOpenId();
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId("KCMVEB8OrTog-Pf8Tefs9ktX5CYbJxkqMSaJa5nl-vg")
                .url("www.baidu.com")
                .build();
        templateMessage.addData(new WxMpTemplateData("first", "您好，您已成为微信【广州爱奇迪】会员。", "#173177"));
        templateMessage.addData(new WxMpTemplateData("type", "18620292076", "#173177"));
        templateMessage.addData(new WxMpTemplateData("address", "广州市白云区广州大道北", "#173177"));
        templateMessage.addData(new WxMpTemplateData("name", "伍华聪", "#173177"));
        templateMessage.addData(new WxMpTemplateData("expDate", "2016年4月18日", "#173177"));
        templateMessage.addData(new WxMpTemplateData("remark", "如有疑问，请咨询18620292076。", "#173177"));
        return wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }
}
